<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { getLocalIcons, getSystemIcons } from '@/utils/icon';
import { ElMessage, ElMessageBox } from 'element-plus';

defineOptions({ name: 'IconPage' });

// 图标类型定义
interface IconItem {
  id: number;
  name: string;
  type?: 'local' | 'system'; // 图标类型：本地图标或系统图标
}

// 本地图标列表 (local-icon)
const localIcons = ref<IconItem[]>([]);
// 系统图标列表 (svg-icon)
const systemIcons = ref<IconItem[]>([]);
// 表格加载状态
const loading = ref(false);
// 当前正在编辑的图标
const currentIcon = ref<IconItem | null>(null);
// 对话框可见性
const dialogVisible = ref(false);
// 对话框类型：edit (修改) 或 add (新增)
const dialogType = ref<'edit' | 'add'>('edit');
// 上传文件
const uploadFile = ref<File | null>(null);

// 分页设置
const pageSize = 5;
const localCurrentPage = ref(1);
const systemCurrentPage = ref(1);

// 分页后的图标数据
const paginatedLocalIcons = computed(() => {
  const start = (localCurrentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return localIcons.value.slice(start, end);
});

const paginatedSystemIcons = computed(() => {
  const start = (systemCurrentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return systemIcons.value.slice(start, end);
});

// 初始化
onMounted(() => {
  loadIcons();
});

// 加载图标列表
function loadIcons() {
  loading.value = true;
  try {
    // 获取本地图标
    const localIconList = getLocalIcons();
    localIcons.value = localIconList.map((name, index) => ({
      id: index + 1,
      name,
      type: 'local'
    }));
    
    // 获取系统图标
    const systemIconList = getSystemIcons();
    systemIcons.value = systemIconList.map((name, index) => ({
      id: index + 1,
      name,
      type: 'system'
    }));
    
    console.log('图标加载完成:', localIcons.value.length, systemIcons.value.length);
  } catch (error) {
    console.error('加载图标失败:', error);
  } finally {
    loading.value = false;
  }
}

// 打开新增图标对话框
function handleAdd() {
  dialogType.value = 'add';
  uploadFile.value = null;
  dialogVisible.value = true;
}

// 编辑图标
function handleEdit(row: IconItem) {
  dialogType.value = 'edit';
  currentIcon.value = row;
  uploadFile.value = null;
  dialogVisible.value = true;
}

// 删除图标
function handleDelete(row: IconItem) {
  if (row.type !== 'local') {
    ElMessage.warning('只能删除本地图标');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除图标 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用后端API删除图标文件
    // 模拟删除成功
    const index = localIcons.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      localIcons.value.splice(index, 1);
      ElMessage.success(`图标 "${row.name}" 删除成功`);
    }
  });
}

// 保存图标修改
function handleSave() {
  if (!uploadFile.value) {
    ElMessage.warning('请选择要上传的图标文件');
    return;
  }
  
  // 检查文件类型
  if (uploadFile.value.type !== 'image/svg+xml') {
    ElMessage.warning('只能上传SVG格式的图标');
    return;
  }
  
  if (dialogType.value === 'add') {
    // 新增逻辑
    // 这里应该调用后端API上传图标文件
    const fileName = uploadFile.value.name.replace('.svg', '');
    
    // 模拟上传成功
    const newId = localIcons.value.length > 0 
      ? Math.max(...localIcons.value.map(icon => icon.id)) + 1 
      : 1;
      
    localIcons.value.push({
      id: newId,
      name: fileName,
      type: 'local'
    });
    
    ElMessage.success(`图标 "${fileName}" 添加成功`);
  } else {
    // 修改逻辑
    if (currentIcon.value) {
      // 这里应该调用后端API上传修改后的图标
      const fileName = uploadFile.value.name.replace('.svg', '');
      
      ElMessage.success(`图标 "${currentIcon.value.name}" 修改成功`);
      
      // 更新本地数据
      if (currentIcon.value.type === 'local') {
        const icon = localIcons.value.find(item => item.id === currentIcon.value?.id);
        if (icon) {
          icon.name = fileName;
        }
      } else {
        const icon = systemIcons.value.find(item => item.id === currentIcon.value?.id);
        if (icon) {
          icon.name = fileName;
        }
      }
    }
  }
  
  dialogVisible.value = false;
  uploadFile.value = null;
}

// 文件选择改变
function handleFileChange(e: Event) {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    uploadFile.value = target.files[0];
  }
}

// 点击图标预览区域触发文件选择
function triggerFileUpload() {
  document.getElementById('icon-upload')?.click();
}
</script>

<template>
  <div class="h-full page-container">
    <!-- 本地图标表格 -->
    <el-card class="mb-16px">
      <template #header>
        <div class="flex justify-between items-center">
          <span>本地图标管理</span>
          <el-button type="primary" @click="handleAdd">新增图标</el-button>
        </div>
      </template>
      
      <el-table 
        :data="paginatedLocalIcons" 
        border 
        v-loading="loading" 
        row-key="id"
        height="250px"
        class="icon-table"
      >
        <el-table-column label="ID" prop="id" width="80" sortable />
        <el-table-column label="图标名称" prop="name" min-width="120" />
        <el-table-column label="图标预览" width="200" align="center">
          <template #default="{ row }">
            <div class="flex-center">
              <svg-icon :local-icon="row.name" class="text-24px" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              修改
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="mt-16px flex justify-end">
        <el-pagination
          v-if="localIcons.length > pageSize"
          background
          layout="prev, pager, next"
          :total="localIcons.length"
          :page-size="pageSize"
          v-model:current-page="localCurrentPage"
        />
      </div>
    </el-card>
    
    <!-- 系统图标表格 -->
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>系统图标表格</span>
        </div>
      </template>
      
      <el-table 
        :data="paginatedSystemIcons" 
        border 
        v-loading="loading" 
        row-key="id"
        height="250px"
        class="icon-table"
      >
        <el-table-column label="ID" prop="id" width="80" sortable />
        <el-table-column label="图标名称" prop="name" min-width="120" />
        <el-table-column label="使用场景" min-width="120">
          <template #default>
            <span class="text-gray-400">系统组件</span>
          </template>
        </el-table-column>
        <el-table-column label="图标预览" width="200" align="center">
          <template #default="{ row }">
            <div class="flex-center">
              <svg-icon :local-icon="row.name" class="text-24px" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="mt-16px flex justify-end">
        <el-pagination
          v-if="systemIcons.length > pageSize"
          background
          layout="prev, pager, next"
          :total="systemIcons.length"
          :page-size="pageSize"
          v-model:current-page="systemCurrentPage"
        />
      </div>
    </el-card>
    
    <!-- 简化的图标上传对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增图标' : '修改图标'" width="400px">
      <!-- 文件上传区域 -->
      <div class="upload-area" @click="triggerFileUpload">
        <!-- 隐藏的文件输入框 -->
        <input 
          id="icon-upload"
          type="file" 
          accept=".svg" 
          @change="handleFileChange"
          class="hidden-input"
        />
        
        <!-- 预览区域 -->
        <div v-if="uploadFile" class="preview-icon">
          <div class="file-name">{{ uploadFile.name }}</div>
          <el-icon class="upload-icon"><Document /></el-icon>
        </div>
        
        <!-- 编辑时显示当前图标 -->
        <div v-else-if="dialogType === 'edit' && currentIcon" class="preview-icon">
          <div class="file-name">{{ currentIcon.name }}.svg</div>
          <svg-icon :local-icon="currentIcon.name" class="text-48px" />
        </div>
        
        <!-- 默认上传提示 -->
        <div v-else class="upload-placeholder">
          <el-icon class="upload-icon"><Upload /></el-icon>
          <div class="upload-text">点击上传SVG图标</div>
        </div>
      </div>
      
      <div class="mt-16px text-center text-sm text-gray-400">
        点击图标区域可{{ dialogType === 'add' ? '上传' : '修改' }}图标
      </div>
      
      <template #footer>
        <div class="flex justify-end gap-10px">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-container {
  overflow-y: auto;
  padding-bottom: 16px;
}

.icon-table {
  width: 100%;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.hidden-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.upload-icon {
  font-size: 32px;
  color: #909399;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
}

.preview-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.file-name {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  word-break: break-all;
}

.text-48px {
  font-size: 48px;
}

.mt-16px {
  margin-top: 16px;
}
</style>
